package leetcode.editor.cn;


public class P405ConvertANumberToHexadecimal {
    public static void main(String[] args) {
        Solution solution = new P405ConvertANumberToHexadecimal().new Solution();
        System.out.println(solution.toHex(-1));

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String toHex(int num) {
            int[] arr = new int[32];
            StringBuilder stringBuilder = new StringBuilder();
            //先转化2进制
            int index = arr.length - 1;
            arr[0] = num >= 0 ? 0 : 1;
            while (num != 0) {
                int value = num % 2;
                arr[index--] = value < 0 ? -value : value;
                num = num / 2;
            }
            if (arr[0] == 1) {
                int add = 1;
                for (int i = 31; i > 0; i--) {
                    arr[i] = arr[i] == 0 ? 1 : 0;
                    if (arr[i] == 1 && add == 1) {
                        arr[i] = 0;
                        add = 1;
                    } else {
                        arr[i] = arr[i] + add;
                        add = 0;
                    }
                }
            }
            char[] arrNum = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    'a', 'b', 'c', 'd', 'e', 'f'};
            for (int i = 0; i < 32; i += 4) {
                int sum = 0;
                for (int step = 3, j = i + step; step >= 0; step--, j--) {
                    sum += arr[j] * Math.pow(2, 3 - step);
                }
                stringBuilder.append(arrNum[sum]);
            }
            while (stringBuilder.indexOf("0") == 0 && stringBuilder.length() > 1) {
                stringBuilder.delete(0, 1);
            }
            return stringBuilder.toString();

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}